<!DOCTYPE html>
<html lang="pt-br">

<head>
   <meta charset="UTF-8">
   <meta http-equiv="X-UA-Compatible" content="IE=edge">
   <meta name="viewport" content="width=device-width, initial-scale=1.0">
   <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"
      integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" 'unsafe-inline'
      crossorigin="anonymous">
   <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"
      integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p"
      crossorigin="anonymous"></script>
   <link rel="shortcut icon" href="/images/logo.png" type="image/x-icon">
   <style>
      code {
         padding: 10px;
         background-color: whitesmoke;
         color: rgb(104, 104, 104);
      }

      pre {
         font-size: 1em;
      }

      .card-code {
         background-color: #f5f5f5;
         border-radius: 8px;
         padding: 20px;
         margin: 10px 0;
         box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
         display: block;
         white-space: pre-wrap;
         word-wrap: break-word;
         font-family: 'Courier New', Courier, monospace;
         color: #333;
         font-size: 14px;
      }
   </style>
   <title>Generate QRCode</title>
</head>

<body>

   <div id="root" class="container mt-5 mb-5 w-50">

      <div id="display-qrcode">
         <h2 class="mb-3 text-secondary">Connect to whatsapp</h2>
         <div class="input-group mb-3">
            <span class="input-group-text" id="basic-addon1">Instance name</span>
            <input id="input-session" type="text" class="form-control" aria-describedby="btn-qr-g" disabled
               value="{{instanceName}}">
            <button id="gen-qrcode" class="btn btn-success" type="submit">Generate qrcode</button>
         </div>

         <hr />

         <div id="qrcode-img"></div>
      </div>
   </div>

   <script src="/js/pixel.js?isDocker={{isDocker}}&env={{env}}&version={{version}}"></script>
   <script src="https://code.jquery.com/jquery-3.6.0.min.js"
      integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
   <script type="module">

      const log = (...data) => console.log(data);

      $('#gen-qrcode').click(() => {
         const headers = { authorization: 'Bearer {{auth.token}}' }
         $.ajax({
            url: `/instance/connect/{{instanceName}}`,
            headers,
            type: 'GET',
            success: (qrcode, status) => {
               
            },
            error: (error) => console.log(error),
         });
      });
      
      //Conexão websocket

      const url = 'ws://localhost:8084/ws/events';
      const reconnectInterval = 5000; // 5 segundos

      function socket(eventName, callback) {
         const ws = new WebSocket(`${url}?event=${encodeURIComponent(eventName)}&token=${encodeURIComponent("{{auth.token}}")}`);

         ws.onopen = () => {
            console.log('Connected to the server');
         };

         ws.onmessage = (event) => {
            if (callback) {
               const data = JSON.parse(event.data)
               callback(data, event)
            }
         };

         ws.onerror = (error) => {
            console.log('Error:', error);
         };

         ws.onclose = (event) => {
            console.log(`Connection closed with code ${event.code} and reason ${event.reason}, attempting to reconnect...`);
            setTimeout(() => socket(event, callback), reconnectInterval);
         };
      }

      // Será criado uma instância da função para cada evento
      // Os eventos são os mesmos disparados pela webhook
      socket("qrcode.updated", (msg, event) => {
         console.log("QRCODE: ", msg)
         $(`#update-qrcode`).remove();
               $('#qrcode-img')
                  .append(
                     `<div id="update-qrcode" class="card mb-2">
                        <h5 class="card-title text-center text-secondary mt-3">{{name}}</h5>
                        <div class="card-body container d-flex justify-content-center">
                           <img class="img-thumbnail mt-2 w-50" alt="qrcode.png"
                              src="${msg.base64}">
                        </div>
                        <div class="card-body">
                           <code class="text-card d-block">${JSON.stringify({ code: msg.code }, null, 2)}</code>
                           <h5 class="card-title text-center text-warning mt-3">Connecting...</h5>
                        </div>
                     </div>`
                  );
      })

      socket("connection.update", (msg, event) => {
         console.log(msg)
      })

      socket("messages.upsert", (msg, event) => {
         console.log(msg)
      })
   </script>
</body>

</html>